import pandas as pd
import numpy as np
import tushare as ts
from datetime import datetime, timedelta
from transformers import BertTokenizer, BertForSequenceClassification
import torch
import matplotlib.pyplot as plt
from lightgbm import LGBMClassifier
import requests
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class HKStockAnalysisSystem:
    def __init__(self, token, risk_aversion=0.8):
        """初始化港股分析系统"""
        self.ts_pro = ts.pro_api(token)
        self.risk_aversion = risk_aversion
        self.stocks_data = {}
        self.models = {}
        self.strategy_weights = {
            'technical': 0.4,
            'fundamental': 0.3,
            'sentiment': 0.2,
            'macro': 0.1
        }
        # 初始化情绪分析模型
        self.tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
        self.sentiment_model = BertForSequenceClassification.from_pretrained(
            'bert-base-chinese', num_labels=3)  # 消极、中性、积极
        
        # 初始化分类模型
        self.trend_classifier = LGBMClassifier(n_estimators=100, random_state=42)
    
    def get_stock_data(self, stock_code, start_date, end_date=None):
        """获取港股历史数据"""
        if end_date is None:
            end_date = datetime.now().strftime('%Y%m%d')
        
        try:
            # 获取日线行情
            df_daily = self.ts_pro.hk_daily(ts_code=stock_code, start_date=start_date, end_date=end_date)
            
            # 获取基本面数据
            df_basic = self.ts_pro.hk_basic(ts_code=stock_code, trade_date=end_date)
            
            # 获取资金流向数据
            df_flow = self.ts_pro.hk_flow(ts_code=stock_code, start_date=start_date, end_date=end_date)
            
            # 合并数据
            df = pd.merge(df_daily, df_flow, on=['ts_code', 'trade_date'])
            df = pd.merge(df, df_basic, on='ts_code')
            
            # 数据预处理
            df['trade_date'] = pd.to_datetime(df['trade_date'])
            df.set_index('trade_date', inplace=True)
            df.sort_index(ascending=True, inplace=True)
            
            self.stocks_data[stock_code] = df
            logger.info(f"成功获取 {stock_code} 数据，共 {len(df)} 条记录")
            return df
        except Exception as e:
            logger.error(f"获取 {stock_code} 数据失败: {e}")
            return None
    
    def calculate_technical_indicators(self, df):
        """计算技术指标"""
        # MACD
        df['EMA12'] = df['close'].ewm(span=12, adjust=False).mean()
        df['EMA26'] = df['close'].ewm(span=26, adjust=False).mean()
        df['MACD'] = df['EMA12'] - df['EMA26']
        df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
        df['Histogram'] = df['MACD'] - df['Signal']
        
        # KDJ
        low_min = df['low'].rolling(window=9).min()
        high_max = df['high'].rolling(window=9).max()
        df['RSV'] = (df['close'] - low_min) / (high_max - low_min) * 100
        df['K'] = df['RSV'].ewm(com=2).mean()
        df['D'] = df['K'].ewm(com=2).mean()
        df['J'] = 3 * df['K'] - 2 * df['D']
        
        # RSI
        delta = df['close'].diff()
        gain = delta.where(delta > 0, 0)
        loss = -delta.where(delta < 0, 0)
        avg_gain = gain.rolling(window=14).mean()
        avg_loss = loss.rolling(window=14).mean()
        rs = avg_gain / avg_loss
        df['RSI'] = 100 - (100 / (1 + rs))
        
        # 波动率
        df['Volatility'] = df['close'].rolling(window=20).std()
        
        # 移动平均线
        df['MA5'] = df['close'].rolling(window=5).mean()
        df['MA10'] = df['close'].rolling(window=10).mean()
        df['MA20'] = df['close'].rolling(window=20).mean()
        df['MA50'] = df['close'].rolling(window=50).mean()
        df['MA100'] = df['close'].rolling(window=100).mean()
        
        # 生成技术信号
        df['MACD_Signal'] = np.where(df['MACD'] > df['Signal'], 1, 
                                    np.where(df['MACD'] < df['Signal'], -1, 0))
        df['KDJ_Signal'] = np.where((df['K'] > df['D']) & (df['K'] < 80), 1, 
                                    np.where((df['K'] < df['D']) & (df['K'] > 20), -1, 0))
        df['RSI_Signal'] = np.where(df['RSI'] < 30, 1, 
                                    np.where(df['RSI'] > 70, -1, 0))
        
        # 综合技术评分
        df['Technical_Score'] = (df['MACD_Signal'] * 0.4 + 
                                df['KDJ_Signal'] * 0.3 + 
                                df['RSI_Signal'] * 0.3)
        
        return df
    
    def analyze_fundamentals(self, df, industry_avg=None):
        """基本面分析"""
        # 计算基本面指标
        df['PE_Ratio'] = df['close'] / df['eps']  # 市盈率
        df['PB_Ratio'] = df['close'] / df['bps']  # 市净率
        df['PS_Ratio'] = df['close'] / df['revenue'] * df['total_share']  # 市销率
        df['ROE'] = df['profit'] / df['net_assets'] * 100  # 净资产收益率
        df['Debt_Ratio'] = df['total_debt'] / df['total_assets'] * 100  # 资产负债率
        
        # 基本面评分 (标准化处理)
        if industry_avg:
            # 对比行业均值评分
            df['PE_Score'] = np.where(df['PE_Ratio'] < industry_avg['PE_Ratio'], 1, 
                                     np.where(df['PE_Ratio'] > industry_avg['PE_Ratio'] * 1.5, -1, 0))
            df['PB_Score'] = np.where(df['PB_Ratio'] < industry_avg['PB_Ratio'], 1, 
                                     np.where(df['PB_Ratio'] > industry_avg['PB_Ratio'] * 1.5, -1, 0))
            df['ROE_Score'] = np.where(df['ROE'] > industry_avg['ROE'], 1, 
                                      np.where(df['ROE'] < industry_avg['ROE'] * 0.8, -1, 0))
            df['Debt_Score'] = np.where(df['Debt_Ratio'] < industry_avg['Debt_Ratio'], 1, 
                                       np.where(df['Debt_Ratio'] > industry_avg['Debt_Ratio'] * 1.2, -1, 0))
        else:
            # 基于历史数据评分
            df['PE_Score'] = np.where(df['PE_Ratio'] < df['PE_Ratio'].quantile(0.3), 1, 
                                     np.where(df['PE_Ratio'] > df['PE_Ratio'].quantile(0.7), -1, 0))
            df['PB_Score'] = np.where(df['PB_Ratio'] < df['PB_Ratio'].quantile(0.3), 1, 
                                     np.where(df['PB_Ratio'] > df['PB_Ratio'].quantile(0.7), -1, 0))
            df['ROE_Score'] = np.where(df['ROE'] > df['ROE'].quantile(0.7), 1, 
                                      np.where(df['ROE'] < df['ROE'].quantile(0.3), -1, 0))
            df['Debt_Score'] = np.where(df['Debt_Ratio'] < df['Debt_Ratio'].quantile(0.3), 1, 
                                       np.where(df['Debt_Ratio'] > df['Debt_Ratio'].quantile(0.7), -1, 0))
        
        # 综合基本面评分
        df['Fundamental_Score'] = (df['PE_Score'] * 0.3 + 
                                  df['PB_Score'] * 0.2 + 
                                  df['ROE_Score'] * 0.4 + 
                                  df['Debt_Score'] * 0.1)
        
        return df
    
    def analyze_sentiment(self, stock_code, start_date, end_date):
        """分析市场情绪"""
        # 获取新闻数据 (模拟API调用)
        news_data = self._get_stock_news(stock_code, start_date, end_date)
        if not news_data:
            return pd.DataFrame()
        
        # 情感分析
        sentiment_scores = []
        for news in news_data:
            score = self._get_sentiment_score(news['content'])
            sentiment_scores.append({
                'date': news['date'],
                'title': news['title'],
                'content': news['content'],
                'sentiment_score': score,
                'sentiment_label': 'positive' if score > 0.2 else ('negative' if score < -0.2 else 'neutral')
            })
        
        # 转换为DataFrame
        df_sentiment = pd.DataFrame(sentiment_scores)
        df_sentiment['date'] = pd.to_datetime(df_sentiment['date'])
        df_sentiment.set_index('date', inplace=True)
        
        # 计算每日情感汇总
        daily_sentiment = df_sentiment.resample('D').agg({
            'sentiment_score': ['mean', 'count'],
            'sentiment_label': lambda x: x.value_counts().index[0] if len(x) > 0 else 'neutral'
        })
        daily_sentiment.columns = ['sentiment_mean', 'news_count', 'dominant_sentiment']
        
        return daily_sentiment
    
    def _get_stock_news(self, stock_code, start_date, end_date):
        """获取股票新闻 (模拟API调用)"""
        # 实际应用中应替换为真实API调用
        logger.info(f"获取 {stock_code} 在 {start_date} 至 {end_date} 的新闻数据")
        # 模拟返回一些新闻数据
        return [
            {
                'date': '2025-06-15',
                'title': f'{stock_code} 发布2025年Q1财报，净利润同比增长18%',
                'content': f'{stock_code} 今日发布2025年第一季度财报，数据显示，公司季度营收达到234亿港元，同比增长12%，净利润56亿港元，同比增长18%，超出市场预期...'
            },
            {
                'date': '2025-06-14',
                'title': f'分析师看好{stock_code}云业务前景，目标价上调至350港元',
                'content': f'国际知名投行发布研究报告，称看好{stock_code}云业务在东南亚市场的拓展前景，预计未来三年复合增长率将达到25%，并将其目标价由320港元上调至350港元...'
            }
        ]
    
    def _get_sentiment_score(self, text):
        """使用BERT模型分析文本情感"""
        # 实际应用中应加载训练好的模型
        inputs = self.tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=128)
        with torch.no_grad():
            outputs = self.sentiment_model(**inputs)
        logits = outputs.logits
        probabilities = torch.softmax(logits, dim=1)
        # 将三分类结果转换为-1到1的分数
        score = probabilities[0][2].item() - probabilities[0][0].item()  # 积极分 - 消极分
        return score
    
    def analyze_macro_factors(self):
        """分析宏观经济因素"""
        # 获取宏观数据 (模拟)
        macro_data = {
            'us_fed_rate': 5.25,  # 美联储利率
            'hkd_usd_rate': 7.84,  # 港币美元汇率
            'china_gdp_growth': 5.3,  # 中国GDP增长率
            'hk_unemployment_rate': 2.8  # 香港失业率
        }
        
        # 宏观风险评分
        if macro_data['us_fed_rate'] > 5.0:
            fed_risk = -0.5
        elif macro_data['us_fed_rate'] < 4.0:
            fed_risk = 0.5
        else:
            fed_risk = 0
        
        if macro_data['hkd_usd_rate'] > 7.85 or macro_data['hkd_usd_rate'] < 7.75:
            exchange_risk = -0.3
        else:
            exchange_risk = 0
        
        if macro_data['china_gdp_growth'] < 5.0:
            gdp_risk = -0.4
        else:
            gdp_risk = 0.2
        
        if macro_data['hk_unemployment_rate'] > 3.5:
            unemployment_risk = -0.3
        else:
            unemployment_risk = 0.1
        
        # 综合宏观评分
        macro_score = fed_risk * 0.4 + exchange_risk * 0.2 + gdp_risk * 0.3 + unemployment_risk * 0.1
        
        return {
            'macro_data': macro_data,
            'macro_score': macro_score
        }
    
    def train_trend_predictor(self, stock_code, features=None, labels=None):
        """训练趋势预测模型"""
        if stock_code not in self.stocks_data:
            logger.error(f"没有 {stock_code} 的数据，无法训练模型")
            return False
        
        df = self.stocks_data[stock_code].copy()
        
        # 如果没有提供特征和标签，则使用默认设置
        if features is None:
            features = ['open', 'high', 'low', 'close', 'vol', 'amount', 
                        'MA5', 'MA10', 'MA20', 'MA50', 'MA100', 
                        'MACD', 'Signal', 'Histogram', 'K', 'D', 'J', 'RSI', 'Volatility']
        
        if labels is None:
            # 创建标签：未来5天收益率 > 3% 为买入(1)，<-3%为卖出(-1)，否则为持有(0)
            df['future_return'] = df['close'].pct_change(5).shift(-5)
            df['label'] = np.where(df['future_return'] > 0.03, 1, 
                                 np.where(df['future_return'] < -0.03, -1, 0))
        
        # 清理缺失值
        df.dropna(subset=features + ['label'], inplace=True)
        
        # 划分训练集和测试集
        train_size = int(len(df) * 0.8)
        X_train, X_test = df[features].iloc[:train_size], df[features].iloc[train_size:]
        y_train, y_test = df['label'].iloc[:train_size], df['label'].iloc[train_size:]
        
        # 训练模型
        self.trend_classifier.fit(X_train, y_train)
        
        # 评估模型
        train_score = self.trend_classifier.score(X_train, y_train)
        test_score = self.trend_classifier.score(X_test, y_test)
        
        logger.info(f"模型训练完成 - 训练集准确率: {train_score:.4f}, 测试集准确率: {test_score:.4f}")
        
        # 保存模型
        self.models[stock_code] = {
            'model': self.trend_classifier,
            'features': features,
            'train_score': train_score,
            'test_score': test_score
        }
        
        return True
    
    def predict_trend(self, stock_code):
        """预测股票趋势"""
        if stock_code not in self.models:
            logger.error(f"没有 {stock_code} 的训练模型，无法进行预测")
            return None
        
        model_info = self.models[stock_code]
        df = self.stocks_data[stock_code].copy()
        
        # 获取最新数据
        latest_data = df[model_info['features']].iloc[-1:].values
        
        # 预测
        prediction = model_info['model'].predict(latest_data)[0]
        probabilities = model_info['model'].predict_proba(latest_data)[0]
        
        # 预测置信度
        confidence = max(probabilities)
        
        return {
            'prediction': prediction,  # -1(卖出), 0(持有), 1(买入)
            'confidence': confidence,
            'prediction_text': '买入' if prediction == 1 else ('卖出' if prediction == -1 else '持有')
        }
    
    def generate_investment_recommendation(self, stock_code):
        """生成投资建议"""
        if stock_code not in self.stocks_data:
            logger.error(f"没有 {stock_code} 的数据，无法生成投资建议")
            return None
        
        df = self.stocks_data[stock_code].copy()
        latest_data = df.iloc[-1]
        
        # 获取各维度评分
        technical_score = latest_data['Technical_Score']
        fundamental_score = latest_data['Fundamental_Score']
        
        # 分析市场情绪
        sentiment_data = self.analyze_sentiment(stock_code, 
                                              (datetime.now() - timedelta(days=30)).strftime('%Y%m%d'),
                                              datetime.now().strftime('%Y%m%d'))
        if not sentiment_data.empty:
            sentiment_score = sentiment_data['sentiment_mean'].iloc[-1]
        else:
            sentiment_score = 0
        
        # 分析宏观因素
        macro_data = self.analyze_macro_factors()
        macro_score = macro_data['macro_score']
        
        # 计算综合评分
        weights = self.strategy_weights
        composite_score = (technical_score * weights['technical'] + 
                          fundamental_score * weights['fundamental'] + 
                          sentiment_score * weights['sentiment'] + 
                          macro_score * weights['macro'])
        
        # 基于评分生成建议
        if composite_score > 0.3:
            recommendation = '强烈买入'
            position_size = 0.25 * self.risk_aversion  # 最大仓位25%
        elif composite_score > 0.1:
            recommendation = '买入'
            position_size = 0.15 * self.risk_aversion  # 最大仓位15%
        elif composite_score > -0.1:
            recommendation = '持有'
            position_size = 0.05 * self.risk_aversion  # 最小仓位5%
        elif composite_score > -0.3:
            recommendation = '卖出'
            position_size = -0.15 * self.risk_aversion  # 减仓15%
        else:
            recommendation = '强烈卖出'
            position_size = -0.25 * self.risk_aversion  # 减仓25%
        
        # 生成止损和目标价格
        current_price = latest_data['close']
        if recommendation in ['买入', '强烈买入']:
            # 基于ATR设置止损和目标
            atr = latest_data['Volatility']
            stop_loss = current_price - atr * 3
            target_price = current_price + atr * 5
        else:
            stop_loss = None
            target_price = None
        
        # 生成投资建议报告
        report = {
            'stock_code': stock_code,
            'date': datetime.now().strftime('%Y-%m-%d'),
            'current_price': current_price,
            'recommendation': recommendation,
            'position_size': f"{position_size*100:.1f}%",
            'stop_loss': stop_loss,
            'target_price': target_price,
            'scores': {
                'technical': technical_score,
                'fundamental': fundamental_score,
                'sentiment': sentiment_score,
                'macro': macro_score,
                'composite': composite_score
            },
            'explanation': self._generate_explanation(
                technical_score, fundamental_score, sentiment_score, macro_score, composite_score
            )
        }
        
        return report
    
    def _generate_explanation(self, technical, fundamental, sentiment, macro, composite):
        """生成投资建议解释"""
        explanations = []
        
        if technical > 0:
            explanations.append(f"技术面显示积极信号，MACD、KDJ和RSI指标均支持看涨趋势。")
        elif technical < 0:
            explanations.append(f"技术面显示消极信号，MACD、KDJ和RSI指标均指向看跌趋势。")
        else:
            explanations.append(f"技术面指标呈现中性，暂无明确趋势信号。")
        
        if fundamental > 0:
            explanations.append(f"基本面强劲，公司盈利和估值指标优于行业平均水平。")
        elif fundamental < 0:
            explanations.append(f"基本面较弱，公司盈利和估值指标落后于行业平均水平。")
        else:
            explanations.append(f"基本面表现中性，与行业平均水平相当。")
        
        if sentiment > 0:
            explanations.append(f"市场情绪积极，近期新闻和分析师评级偏向乐观。")
        elif sentiment < 0:
            explanations.append(f"市场情绪消极，近期负面新闻和分析师下调评级较多。")
        else:
            explanations.append(f"市场情绪中性，多空消息较为平衡。")
        
        if macro > 0:
            explanations.append(f"宏观经济环境有利，美联储政策、汇率和GDP增长等因素提供支撑。")
        elif macro < 0:
            explanations.append(f"宏观经济环境面临挑战，美联储政策收紧、汇率波动或GDP增长放缓带来压力。")
        else:
            explanations.append(f"宏观经济环境中性，对市场影响有限。")
        
        if composite > 0.3:
            explanations.append(f"综合各维度分析，强烈建议买入，各因素均显示积极信号。")
        elif composite > 0.1:
            explanations.append(f"综合各维度分析，建议买入，多数因素支持上涨。")
        elif composite > -0.1:
            explanations.append(f"综合各维度分析，建议持有，多空因素较为平衡。")
        elif composite > -0.3:
            explanations.append(f"综合各维度分析，建议卖出，多数因素指向下跌。")
        else:
            explanations.append(f"综合各维度分析，强烈建议卖出，各因素均显示消极信号。")
        
        return "\n".join(explanations)
    
    def backtest_strategy(self, stock_code, start_date, end_date, initial_capital=100000):
        """回测策略"""
        if stock_code not in self.stocks_data:
            logger.error(f"没有 {stock_code} 的数据，无法进行回测")
            return None
        
        df = self.stocks_data[stock_code].copy()
        df = df[(df.index >= start_date) & (df.index <= end_date)]
        
        # 初始化资金和持仓
        capital = initial_capital
        position = 0
        trades = []
        
        # 回测
        for i in range(10, len(df)):  # 从第10天开始，确保有足够数据计算指标
            # 获取当前日期和数据
            current_date = df.index[i]
            current_price = df['close'].iloc[i]
            
            # 计算技术指标 (使用截至前一天的数据)
            hist_data = df.iloc[:i].copy()
            hist_data = self.calculate_technical_indicators(hist_data)
            latest_data = hist_data.iloc[-1]
            
            # 获取技术评分
            technical_score = latest_data['Technical_Score']
            
            # 模拟基本面评分 (简化处理)
            fundamental_score = np.random.uniform(-0.5, 0.5)  # 实际应使用历史基本面数据
            
            # 模拟情绪评分
            sentiment_score = np.random.uniform(-0.3, 0.3)  # 实际应使用历史情绪数据
            
            # 模拟宏观评分
            macro_score = np.random.uniform(-0.2, 0.2)  # 实际应使用历史宏观数据
            
            # 计算综合评分
            weights = self.strategy_weights
            composite_score = (technical_score * weights['technical'] + 
                              fundamental_score * weights['fundamental'] + 
                              sentiment_score * weights['sentiment'] + 
                              macro_score * weights['macro'])
            
            # 生成交易信号
            if composite_score > 0.2:
                signal = 1  # 买入
            elif composite_score < -0.2:
                signal = -1  # 卖出
            else:
                signal = 0  # 持有
            
            # 执行交易
            if signal == 1 and position == 0:  # 买入
                shares_to_buy = int(capital * 0.8 / current_price)  # 使用80%资金
                if shares_to_buy > 0:
                    position = shares_to_buy
                    capital -= shares_to_buy * current_price
                    trades.append({
                        'date': current_date,
                        'type': 'buy',
                        'price': current_price,
                        'shares': shares_to_buy,
                        'capital': capital,
                        'position': position
                    })
            
            elif signal == -1 and position > 0:  # 卖出
                capital += position * current_price
                trades.append({
                    'date': current_date,
                    'type': 'sell',
                    'price': current_price,
                    'shares': position,
                    'capital': capital,
                    'position': 0
                })
                position = 0
        
        # 计算最终资产
        if position > 0:
            final_value = capital + position * df['close'].iloc[-1]
        else:
            final_value = capital
        
        # 计算绩效指标
        total_return = (final_value - initial_capital) / initial_capital
        annual_return = (1 + total_return) ** (252 / len(df)) - 1
        
        # 计算最大回撤
        portfolio_values = []
        peak = initial_capital
        max_drawdown = 0
        
        for trade in trades:
            if trade['type'] == 'buy':
                portfolio_value = trade['capital'] + trade['shares'] * trade['price']
            else:
                portfolio_value = trade['capital']
            
            portfolio_values.append(portfolio_value)
            
            if portfolio_value > peak:
                peak = portfolio_value
            
            drawdown = (portfolio_value - peak) / peak
            if drawdown < max_drawdown:
                max_drawdown = drawdown
        
        # 计算夏普比率 (简化，使用日收益率)
        daily_returns = df['close'].pct_change().dropna()
        risk_free_rate = 0.02 / 252  # 假设无风险利率为2%年化
        sharpe_ratio = (daily_returns.mean() - risk_free_rate) / daily_returns.std() * np.sqrt(252)
        
        # 生成回测报告
        report = {
            'start_date': start_date,
            'end_date': end_date,
            'initial_capital': initial_capital,
            'final_value': final_value,
            'total_return': f"{total_return*100:.2f}%",
            'annual_return': f"{annual_return*100:.2f}%",
            'max_drawdown': f"{abs(max_drawdown)*100:.2f}%",
            'sharpe_ratio': f"{sharpe_ratio:.2f}",
            'num_trades': len(trades),
            'trades': trades
        }
        
        return report

# 使用示例
if __name__ == "__main__":
    # 初始化系统
    token = "your_tushare_token"  # 替换为你的Tushare token
    system = HKStockAnalysisSystem(token, risk_aversion=0.8)
    
    # 获取腾讯控股(00700.HK)数据
    stock_code = "00700.HK"
    system.get_stock_data(stock_code, start_date="20240101")
    
    # 计算技术指标
    df = system.calculate_technical_indicators(system.stocks_data[stock_code])
    
    # 基本面分析 (使用行业平均数据)
    industry_avg = {
        'PE_Ratio': 21.2,
        'PB_Ratio': 2.5,
        'ROE': 18.5,
        'Debt_Ratio': 45.0
    }
    df = system.analyze_fundamentals(df, industry_avg)
    
    # 训练趋势预测模型
    system.train_trend_predictor(stock_code)
    
    # 生成投资建议
    recommendation = system.generate_investment_recommendation(stock_code)
    
    # 打印建议
    print(f"股票代码: {recommendation['stock_code']}")
    print(f"日期: {recommendation['date']}")
    print(f"当前价格: {recommendation['current_price']}")
    print(f"投资建议: {recommendation['recommendation']}")
    print(f"仓位建议: {recommendation['position_size']}")
    if recommendation['stop_loss']:
        print(f"止损价格: {recommendation['stop_loss']:.2f}")
    if recommendation['target_price']:
        print(f"目标价格: {recommendation['target_price']:.2f}")
    
    print("\n评分详情:")
    for key, value in recommendation['scores'].items():
        print(f"  {key.capitalize()}: {value:.2f}")
    
    print("\n分析说明:")
    print(recommendation['explanation'])
    
    # 回测策略
    backtest_result = system.backtest_strategy(stock_code, "20240101", "20250601")
    print("\n回测结果:")
    print(f"回测期间: {backtest_result['start_date']} 至 {backtest_result['end_date']}")
    print(f"初始资金: {backtest_result['initial_capital']}")
    print(f"最终资产: {backtest_result['final_value']:.2f}")
    print(f"总收益率: {backtest_result['total_return']}")
    print(f"年化收益率: {backtest_result['annual_return']}")
    print(f"最大回撤: {backtest_result['max_drawdown']}")
    print(f"夏普比率: {backtest_result['sharpe_ratio']}")
    print(f"交易次数: {backtest_result['num_trades']}")    